package cn.pzhuweb.util;


import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

public class DBUtil {
    private static String driver = null;
    private static String url = null;
    private static String user = null;
    private static String password = null;

    static {
        // 读取配置文件中的4个基本信息
        InputStream inputStream = DBUtil.class.getClassLoader().getResourceAsStream("db.properties");
        Properties pros = new Properties();
        try {
            pros.load(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
        driver = pros.getProperty("driver");
        url = pros.getProperty("url");
        user = pros.getProperty("user");
        password = pros.getProperty("password");
        try {
            Class.forName(driver);
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public static Connection getConnection() {
        try {
            return DriverManager.getConnection(url, user, password);
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return null;
        }
    }

    public static void close(ResultSet res, Statement sta, Connection con) {
        if (res != null) {
            try {
                res.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        if (sta != null) {
            try {
                sta.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        if (con != null) {
            try {
                con.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    public static void close(ResultSet res, PreparedStatement sta, Connection con) {
        close(res, (Statement) sta, con);
    }

    public static void close(Statement sta, Connection con) {
        close(null, sta, con);
    }

    public static void close(PreparedStatement sta, Connection con) {
        close(null, sta, con);
    }

}
